package org.jianfa.learn.jpa.controller;

import org.jianfa.learn.jpa.entity.ResumeEntity;
import org.jianfa.learn.jpa.repository.ResumeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/")
public class ResumeController {

    @Autowired
    private ResumeRepository resumeRepository;

    @GetMapping("resumes")
    public String findAllResumes(Model model) {
        List<ResumeEntity> resumeEntityList = resumeRepository.findAll();
        model.addAttribute("resumeEntityList", resumeEntityList);
        return "resumes";
    }

    @GetMapping("resume")
    public String findById(Long id, Model model) {
        if (id != null) {
            ResumeEntity resumeEntity = resumeRepository.findById(id).get();
            model.addAttribute("resumeEntity", resumeEntity);
        } else {
            ResumeEntity resumeEntity = new ResumeEntity();
            model.addAttribute("resumeEntity", resumeEntity);
        }
        return "resume";
    }

    @PostMapping("edit")
    public String editResume(ResumeEntity resumeEntity) {
        resumeRepository.save(resumeEntity);
        System.out.println(resumeEntity);
        return "redirect:resumes";
    }

    @DeleteMapping("delete")
    public String deleteResume(Long id) {
        resumeRepository.deleteById(id);
        return "redirect:resumes";
    }

}
